package com.hb.game.pk.ui.activity.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hb.game.pk.APP;
import com.hb.game.pk.R;
import com.hb.game.pk.api.Host;
import com.hb.game.pk.api.RedBag;
import com.hb.game.pk.base.BaseActivity;
import com.hb.game.pk.beans.Login;
import com.hb.game.pk.beans.SendCode;
import com.hb.game.pk.network.RetrofitCreateHelper;
import com.hb.game.pk.ui.MainActivity;
import com.hb.game.pk.utils.LogUtils;
import com.hb.game.pk.utils.SpUtils;
import com.hb.game.pk.utils.StringUtils;
import com.hb.game.pk.utils.TimerCountUtils;
import com.hb.game.pk.utils.ToastUtils;
import com.google.gson.Gson;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.hb.game.pk.network.okhttp.TokenInterceptor.UTF8;

public class LoginActivity extends BaseActivity<Login> {
    @BindView(R.id.tv_type_password)
    TextView tvTypePassword;
    @BindView(R.id.tv_type_code)
    TextView tvTypeCode;
    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.ll_password)
    LinearLayout llPassword;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.ll_code)
    LinearLayout llCode;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    private CountDownTimer timer;
    private int type = 0;
    Call<SendCode> smsCode;
    boolean is_auto;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected int getRootViewId() {
        return R.id.layout_root;
    }

    @Override
    protected int getRefreshId() {
        return 0;
    }

    @Override
    protected int getListViewId() {
        return 0;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
//        checkedType(tvTypePassword, tvTypeCode);
        Intent intent = getIntent();
        is_auto = intent.getBooleanExtra("is_auto", true);
        tvCode.setEnabled(false);
        btnLogin.setEnabled(false);
    }

    @Override
    protected void onRefreshData() {
        super.onRefreshData();
        long l = System.currentTimeMillis();
        String s = (l / 1000) + "";
        Request build = new Request.Builder().url(Host.RE_HOST + "urllist.txt?=" + s).get().build();
        okhttp3.Call call1 = RetrofitCreateHelper.getOkHttpClient().newCall(build);
        call1.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                ToastUtils.showToast("获取地址失败");
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                ResponseBody body = response.body();
                BufferedSource source = body.source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();
                long contentLength = body.contentLength();
                Charset charset = UTF8;
                MediaType contentType = body.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }
                if (contentLength != 0) {
                    String s = buffer.clone().readString(charset);
                    String replace = s.replace("{", "");
                    String replace1 = replace.replace("\"weburl\":", "");
                    String replace3 = replace1.replace("\"socketurl\":", "");
                    String replace4 = replace3.replace("\"", "");
                    String replace5 = replace4.replace("}", "");
                    String[] split = replace5.split(",");
                    Host.HOST = split[0].trim();
                    Host.SOCKETHOST = "ws://" + split[1].trim();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btnLogin.setEnabled(true);
                            tvCode.setEnabled(true);
                        }
                    });
                    if (is_auto) {
                        String uid = SpUtils.getString(LoginActivity.this, "uid", "");
                        String toke = SpUtils.getString(LoginActivity.this, "toke", "");
                        String userInfo = SpUtils.getString(LoginActivity.this, "userInfo", "");
                        if (!StringUtils.isEmpty(uid) && !StringUtils.isEmpty(toke)) {
                            APP.uid = uid;
                            APP.Token = toke;
                            APP.userInfo = new Gson().fromJson(userInfo, Login.DataBean.class);
                            startActivity(MainActivity.class);
                            LoginActivity.this.finish();
                        }
                    }
                } else {
                    ToastUtils.showToast("获取地址失败");
                }
            }
        });
    }

    @OnClick({R.id.tv_type_password, R.id.tv_type_code, R.id.tv_code, R.id.btn_login, R.id.tv_forget})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_type_password:
                type = 0;
                etUsername.setHint("请输入用户名");
                llCode.setVisibility(View.GONE);
                llPassword.setVisibility(View.VISIBLE);
                checkedType(tvTypePassword, tvTypeCode);
                break;
            case R.id.tv_type_code:
                type = 1;
                etUsername.setHint("请输入手机号");
                llPassword.setVisibility(View.GONE);
                llCode.setVisibility(View.VISIBLE);
                checkedType(tvTypeCode, tvTypePassword);
                break;
            case R.id.tv_code:
                if (StringUtils.isEmpty(etUsername.getText().toString())) {
                    ToastUtils.showToast("手机号不能为空");
                    return;
                }
                if (!StringUtils.isPhoneNumberValid(etUsername.getText().toString())) {
                    ToastUtils.showToast("手机号格式不正确");
                    return;
                }
                if (!TimerCountUtils.status) {
                    timer = TimerCountUtils.getTimer(tvCode);
                    timer.start();
                    smsCode = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).getCode(etUsername.getText().toString());
                    smsCode.enqueue(new Callback<SendCode>() {
                        @Override
                        public void onResponse(Call<SendCode> call, Response<SendCode> response) {
                            SendCode body = response.body();
                            if (body == null) {
                                ToastUtils.showToast("请求错误");
                                return;
                            }
                            ToastUtils.showToast(body.getInfo());
                        }

                        @Override
                        public void onFailure(Call<SendCode> call, Throwable t) {
                            ToastUtils.showToast("网络请求错误");
                        }
                    });
                }
                break;
            case R.id.btn_login:
                String username = etUsername.getText().toString();
                String password = "";
                String code = "";
                if (type == 0) {
                    if (StringUtils.isEmpty(username)) {
                        ToastUtils.showToast("用户名不能为空");
                        return;
                    }
                    password = etPassword.getText().toString();
                    if (StringUtils.isEmpty(password)) {
                        ToastUtils.showToast("密码不能为空");
                        return;
                    }
                    call = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).loginPWD(username, password);
                    call.enqueue(new Callback<Login>() {
                        @Override
                        public void onResponse(Call<Login> call, Response<Login> response) {
                            saveLoginInfo(response);
                        }

                        @Override
                        public void onFailure(Call<Login> call, Throwable t) {
                            ToastUtils.showToast("网络请求错误");
                            t.printStackTrace();
                        }
                    });
                } else {
                    if (StringUtils.isEmpty(username)) {
                        ToastUtils.showToast("手机号不能为空");
                        return;
                    }
                    if (!StringUtils.isPhoneNumberValid(username)) {
                        ToastUtils.showToast("手机号格式不正确");
                        return;
                    }
                    code = etCode.getText().toString();
                    if (StringUtils.isEmpty(code)) {
                        ToastUtils.showToast("验证码不能为空");
                        return;
                    }
                    call = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).loginMobile(username, code);
                    call.enqueue(new Callback<Login>() {
                        @Override
                        public void onResponse(Call<Login> call, Response<Login> response) {
                            saveLoginInfo(response);
                        }

                        @Override
                        public void onFailure(Call<Login> call, Throwable t) {
                            ToastUtils.showToast("网络请求错误");
                        }
                    });
                }
                break;
            case R.id.tv_forget:
//                startActivity(ForgetPwdActivity.class);
                break;
        }
    }

    private void saveLoginInfo(Response<Login> response) {
        Login body = response.body();
        if (body == null) {
            ToastUtils.showToast("请求错误");
            return;
        }

        if (body.getStatus() != 1) {
            ToastUtils.showToast(body.getInfo());
            return;
        }

        APP.uid = body.getData().getUser_id();
        APP.Token = body.getData().getToken();
        APP.userInfo = body.getData();
        SpUtils.putString(LoginActivity.this, "uid", body.getData().getUser_id());
        SpUtils.putString(LoginActivity.this, "toke", body.getData().getToken());
        SpUtils.putString(LoginActivity.this, "userInfo", new Gson().toJson(body.getData()));
        startActivity(MainActivity.class);
        this.finish();
    }

    private void checkedType(TextView checked, TextView noChecked) {
        checked.setTextColor(getResources().getColor(R.color.c_000000));
//        checked.setBackgroundResource(R.drawable.login_type_checked_list);
        noChecked.setBackgroundDrawable(null);
        noChecked.setTextColor(getResources().getColor(R.color.c_A59A9C));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            TimerCountUtils.status = false;
            timer.cancel();
        }
        if (smsCode != null) {
            smsCode.cancel();
        }
    }

    public static String getParamByRex(String json, String regex) {

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(json);
        String result = null;
        while (matcher.find()) {
            result = matcher.group(0);
        }
        return result;
    }
}
